package id.co.smltech.servo.project.rest;

import id.co.smltech.servo.project.ejb.ActivityTrackingAdministration;
import id.co.smltech.servo.project.utils.SystemConfiguration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;


@Path("/activityTracking")
public class ActivityTrackingRest {
	@EJB ActivityTrackingAdministration activityTrackingAdministration;
	@EJB SystemConfiguration systemConfiguration;
	
	@POST
	@Path("/uploadFileActivityToGrid")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces(MediaType.TEXT_PLAIN)
	public Response uploadFileExcelLinkInsert(@FormDataParam("uploadFileExcelLinkInsert") InputStream inputStream, 
		    @FormDataParam("uploadFileExcelLinkInsert") FormDataContentDisposition formData
		    ){
		
		systemConfiguration.init();
		String msg = "";

		try{
			
			String uploadDir = systemConfiguration.getDirUploadActivityTracking();
			String fileName = formData.getFileName();
			
			String[] splitFileName = new String[0];
			String os = systemConfiguration.getOs();
			if(os.equalsIgnoreCase("unix"))
				splitFileName = fileName.split("/");
			else if(os.equalsIgnoreCase("windows"))
				splitFileName = fileName.split("\\.");
			else//make default
				splitFileName = fileName.split("/");
			
			String ext = "xls";
			System.out.println("len split of file name : "+splitFileName.length);
			if(splitFileName.length >= 2)
				ext = splitFileName[splitFileName.length-1];
			else
				ext = splitFileName[0];
			
			Date date = new Date();
			DateFormat dateTimeFormatForUploadName = new SimpleDateFormat("yyyyMMddHHmmss");
			
			String fileUpload = dateTimeFormatForUploadName.format(date)+"_"+"userId"+"_upload-file-excel-link."+ext;
			
			long fileSize = formData.getSize();
			System.out.println("File Size : "+fileSize);
			
			
			int check = 0;
			check = writeToFile(inputStream, uploadDir+fileUpload, fileSize);
			inputStream.close();
			
			if(check == 1){
				msg = "upload finished : "+fileName+" and renamed to be : "+fileUpload;
				activityTrackingAdministration.uploadFileExcelSims();
			}
			else
				msg = "upload failed";	
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return Response.status(200).entity(msg).build(); 
	}
	
	
	@GET
	@Path("/downloadTemplateActivity")
	public Response downloadLinks() {
		return activityTrackingAdministration.downloadTemplate();
	}

	// save uploaded file to new location
	private int writeToFile(InputStream inputStream, String uploadedFileLocation, long fileSize){
		
		int check = 0;
		
		try{
			OutputStream outputStream = new FileOutputStream(new File(uploadedFileLocation));
			int read = 0;
			//read standarnya 1024 bytes, harus disetting di glassfish-nya utk naikin read sizenya
			int sizeByte = 1024*1024*10; //10 MB
			long sizeRead = 0;
			
			byte[] bytes = new byte[sizeByte];
			while((read = inputStream.read(bytes)) != -1){
				outputStream.write(bytes, 0, read);
				System.out.print("read : "+read+" | File Size : "+fileSize);
				
//				sizeRead += read;
//				if(sizeRead == fileSize)
					check = 1;
			}
			
			outputStream.flush();
			outputStream.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return check;
	}
	
	
	@GET
	@Path("/hello")
	public String helloWorld() {
		return "Hello Saya Ganteng Sekali";
	}

}
